package com.fly.locks.thread.atomic;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicLong;

import org.springframework.util.StopWatch;

import lombok.extern.slf4j.Slf4j;

/**
 * @description 压测AtomicLong的原子操作性能
 **/
@Slf4j
public class AtomicLongRunable implements Runnable
{
    private static AtomicLong atomicLong = new AtomicLong(0);
    
    @Override
    public void run()
    {
        for (int i = 0; i < 10000; i++)
        {
            atomicLong.incrementAndGet();
        }
    }
    
    public static void main(String[] args)
    {
        ExecutorService es = Executors.newFixedThreadPool(30);
        Runnable runnable = new AtomicLongRunable();
        StopWatch clock = new StopWatch();
        clock.start();
        for (int i = 0; i < 10000; i++)
        {
            es.submit(runnable);
        }
        es.shutdown();
        // 保证任务全部执行完
        while (!es.isTerminated())
        {
        }
        clock.stop();
        log.info("AtomicLong 运行 {} ms", clock.getLastTaskTimeMillis());
        log.info("AtomicLong add result= {}", atomicLong.get());
    }
}